<template>
  <div>
    <el-form class="login-form" ref="formRef" :model="form" :rules="rules">
      <el-form-item>
        <h2>小鹿线基础框架</h2>
      </el-form-item>

      <el-form-item prop="username">
        <el-input size="large" v-model="form.username" placeholder="用户名">
        </el-input>
      </el-form-item>

      <el-form-item prop="password">
        <el-input
          size="large"
          v-model="form.password"
          placeholder="密码"
          show-password
        >
        </el-input>
      </el-form-item>

      <el-form-item prop="captcha">
        <div class="captchaCode">
          <el-input
            size="large"
            v-model="form.captcha"
            :maxlength="4"
            show-word-limit
            placeholder="验证码"
          >
          </el-input>
          <el-image
            class="verificationCode"
            :src="verificationCode.src"
            @click="loadVerificationCode"
          >
          </el-image>
        </div>
      </el-form-item>

      <el-form-item>
        <el-checkbox v-model="memoPassword"> 记住密码 </el-checkbox>
      </el-form-item>

      <el-form-item>
        <el-button
          class="login"
          size="large"
          type="primary"
          @click="login(formRef)"
        >
          登录
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script setup>
import { onMounted, reactive,ref } from "vue";
// api
import { imageCode, loginByJson } from "@/utils/api/login";
// aes
import { Encrypt } from "@/utils/aes.js";
// pinia
import { useGlobalUserStore } from "@/store/userGlobalStore.js";
import { useGlobalStore } from "@/store/GlobalStore.js";
// 路由
import { useRouter } from "vue-router";
let router = useRouter();

const rules = reactive({
  username: [{ required: true, message: "用户名是必填项", trigger: "blur" }],
  password: [{ required: true, message: "用户密码是必填项", trigger: "blur" }],
  captcha: [{ required: true, message: "请输入验证码", trigger: "blur" }],
});
const form = reactive({
  username: "",
  password: "",
  captcha: "",
});
const formRef = ref("");
const verificationCode = reactive({
  src: "",
  curKey: "",
});
//记住密码
const memoPassword = localStorage.getItem("memoPassword") === "true" ? true : false;
onMounted(() => {
  init();
});
const init = () => {
  loadVerificationCode();
};
//获取验证码==》图
const loadVerificationCode = async () => {
  let key = new Date().getTime();//随机uuid
  let res = await imageCode({ key });
  const blob = new Blob([res], { type: "application/vnd.ms-excel" });
  const url = URL.createObjectURL(blob);
  verificationCode.src = url;
  verificationCode.curKey = key;
};
//登录
const login = (formEl) => {
  if (!formEl) return;

  formEl.validate(async (valid, fields) => {
    if (valid) {
      let res = await loginByJson({
        username: Encrypt(form.username), //用户名（需要使用AES加密）
        password: Encrypt(form.password), //密码（需要使用AES加密）
        key: verificationCode.curKey,
        captcha: form.captcha,
      });
      // 存储token【在请求拦截器中使用】
      localStorage.setItem("TOKEN", res.data);
      // 获取用户信息，拿到角色权限等信息【在store里发异步请求】
      let store = useGlobalUserStore();
      store.getGlobalUserInfo();
      //记住密码
      setMemoPassword();
      ElMessage({
        showClose: true,
        message: "登录成功",
        type: "success",
      });
      //跳转到首页
      router.push("/");
    } else {
      ElMessage({
        showClose: true,
        message: "请输入正确格式",
        type: "warning",
      });
    }
  });
};
//记住密码函数体
const setMemoPassword = () => {
  if (!memoPassword) {
    localStorage.setItem("memoPassword", true);
  }
};
</script>
<style>
.login-form {
  width: 350px;
  margin: 10% auto;
}
h2 {
  margin: 0 auto;
}
.captchaCode {
  display: flex;
}
.verificationCode {
  margin-left: 10px;
}
.login {
  width: 350px;
}
</style>
